package top.itaso.lib.widget.tpv;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import top.itaso.lib.widget.R;

/**
 * @Description: IWB 系统设置-应用管理：应用分类使用的 TitleBar 自定义控件
 * @Author: itsdf07
 * @CreateDate: 2022/09/01
 */
public class TpvSettingsTitleBarView2AppsFilter extends TpvSettingsTitleBarView {
    private final String TAG = this.getClass().getSimpleName();
    private String[] appState;

    /**
     * Title 标题
     */
    private TextView tvTitleBarContent;
    /**
     * APP 过滤窗口 打开/关闭 状态 ICON
     */
    private ImageView ivFilterWindowStatus;

    private AppStateAdapter appStateAdapter;

    private PopupWindow appFilterPopup;
    /**
     * appFilterPopup 的宽度 = tvTitleBarContent 宽度 + 向下箭头宽度
     */
    private int appFilterPopupWidth = 0;

    private RecyclerView appStateFilterList;

    private IAppFilterItemListener itemListener;

    public interface IAppFilterItemListener {
        /**
         * @param content  选择项 文案
         * @param position 选择项 索引
         */
        void onItemSelected(String content, int position);
    }

    public TpvSettingsTitleBarView2AppsFilter(Context context) {
        this(context, null);
    }

    public TpvSettingsTitleBarView2AppsFilter(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TpvSettingsTitleBarView2AppsFilter(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        appState = context.getResources().getStringArray(R.array.array_app_state);
        initView();
    }

    private void initView() {
        tvTitleBarContent = createAppFilterContentTextView();
        tvTitleBarContent.setFocusable(true);
        tvTitleBarContent.setText(appState[3]);
        tvTitleBarContent.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Log.d(TAG, "onFocusChange: >>>>>>" + v + " focus state is " + hasFocus);
                ((TextView) v).setTextColor(colorTitleContent(hasFocus));
            }
        });

        ivFilterWindowStatus = createArrowImageView();

        onRotation(ivFilterWindowStatus, 0);
        addTitleBarContent(tvTitleBarContent, ivFilterWindowStatus)
                .setLayoutReadyOk();


        appStateFilterList = new RecyclerView(getContext());
        appStateFilterList.setBackground(getResources().getDrawable(R.drawable.ic_tpv_filter_app_bg));
//        appStateFilterList.setPadding(getResources().getDimensionPixelSize(R.dimen.dimen_3),
//                getResources().getDimensionPixelSize(R.dimen.dimen_3),
//                getResources().getDimensionPixelSize(R.dimen.dimen_3),
//                getResources().getDimensionPixelSize(R.dimen.dimen_3));
        appStateFilterList.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        appStateAdapter = new AppStateAdapter();
        appStateFilterList.setAdapter(appStateAdapter);

        tvTitleBarContent.setOnClickListener(new OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: >>>>>>TitleBarContent[" + v + "] has clicked");
                showFilterAppsWindow(v);
            }
        });
    }

    @Override
    public final boolean isShowBack() {
        return true;
    }

    public void setItemListener(IAppFilterItemListener itemListener) {
        this.itemListener = itemListener;
    }

    /**
     * 过滤应用列表分类的交互窗口-Popupwindow 实现
     *
     * @param anchor
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void showFilterAppsWindow(View anchor) {
        onRotation(ivFilterWindowStatus, 180);
//        ivFilterWindowStatus.setImageDrawable(getContext().getResources().getDrawable(R.mipmap.icon_app_sort_up_arrow));
        if (appFilterPopup == null) {
            appFilterPopup = new PopupWindow();
            appFilterPopup.setContentView(appStateFilterList);//设置要弹出的界面
//        appFilterPopup.setWidth(DrawerLayout.LayoutParams.WRAP_CONTENT);//设置弹出框的尺寸为适应控件
            appFilterPopup.setWidth(appFilterPopupWidth);//设置弹出框的尺寸为适应控件

            appFilterPopup.setHeight(DrawerLayout.LayoutParams.WRAP_CONTENT);
            appFilterPopup.setFocusable(true);
            appFilterPopup.setOutsideTouchable(true);

//            appFilterPopup.setBackgroundDrawable(getContext().getDrawable(R.drawable.shape_bg_radius_0_1));
            appFilterPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    Log.v(TAG, "onDismiss: >>>>>>");
                    onRotation(ivFilterWindowStatus, 0);
//                ivFilterWindowStatus.setImageDrawable(getContext().getResources().getDrawable(R.mipmap.icon_app_sort_down_arrow));
                }
            });
        }
        appFilterPopup.showAsDropDown(anchor);
    }

    public void closeFilterAppsWindow() {
        if (appFilterPopup != null) {
            appFilterPopup.dismiss();
        }
    }

    /**
     * 创建 应用管理 中过滤应用类别右侧的 箭头视图
     *
     * @return
     */
    private ImageView createArrowImageView() {
        ImageView imageView = new ImageView(getContext());
        imageView.setImageDrawable(getContext().getResources().getDrawable(R.mipmap.ic_more_down));
        int padding = dp2px(getContext(), 3);
        imageView.setPadding(padding, padding, padding, padding);
        int height = dp2px(getContext(), 25);
        appFilterPopupWidth += height;
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(height, height);
        imageView.setLayoutParams(params);
        return imageView;
    }

    /**
     * 创建 应用管理 中过滤应用类别视图
     *
     * @return
     */
    private TextView createAppFilterContentTextView() {
        TextView textView = createTitleContentTextView();
//        textView.setMinWidth(dp2px(getContext(), 85));
        LayoutParams params = (LayoutParams) textView.getLayoutParams();
        if (params == null) {
            params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        }
        params.width = dp2px(getContext(), 85);
        appFilterPopupWidth += params.rightMargin + params.width;
        params.rightMargin = 0 - getChildViewRightMargin();//去掉右边距
        textView.setLayoutParams(params);

        return textView;
    }


    private class AppStateAdapter extends RecyclerView.Adapter<AppStateAdapter.AppStateViewHolder> {
        private int createViewposition = 0;

        public AppStateAdapter() {
            this.createViewposition = 0;
        }

        @Override
        public AppStateViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            TextView filterItem = new TextView(parent.getContext());
            filterItem.setFocusable(true);
            filterItem.setBackground(getResources().getDrawable(R.drawable.selector_bg_rectangular));
            filterItem.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
            filterItem.setPadding(dp2px(getContext(), 5),
                    0,
                    0,
                    0);
            filterItem.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
            int margin = dp2px(getContext(), 3);
            params.setMargins(margin, margin, margin, (createViewposition < appState.length - 1) ? 0 : margin);//动态设置Item的外边距，为了每个Item的间距相同，故除最后一个之外，其他都只设置左上右
            params.height = dp2px(getContext(), 34);
//            params.width = appFilterPopupWidth;// (dp2px(getContext(), 95));
            filterItem.setLayoutParams(params);
            createViewposition++;
            return new AppStateViewHolder(filterItem);
        }

        @Override
        public void onBindViewHolder(@NonNull AppStateViewHolder viewHolder, @SuppressLint("RecyclerView") int position) {
            String appStateItem = appState[position];
            viewHolder.tvAppStateitem.setText(appStateItem);
            if (appStateItem.equals(tvTitleBarContent.getText().toString())) {
                viewHolder.itemView.setSelected(true);
            } else {
                viewHolder.itemView.setSelected(false);
            }
            viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (appFilterPopup != null) {
                        appFilterPopup.dismiss();
                    }
                    tvTitleBarContent.setText(appStateItem);
                    notifyDataSetChanged();//操作了 新选中的 Item 之后，需要刷新一下列表，才会重新更新状态
                    if (itemListener != null) {
                        itemListener.onItemSelected(tvTitleBarContent.getText().toString(), position);
                    }
                }
            });
        }

        @Override
        public int getItemCount() {
            return appState.length;
        }

        class AppStateViewHolder extends RecyclerView.ViewHolder {
            private TextView tvAppStateitem;

            public AppStateViewHolder(View itemView) {
                super(itemView);
                tvAppStateitem = (TextView) itemView;
            }
        }

    }

    private void onRotation(View view, int rotation) {
        view.setPivotX(view.getWidth() / 2);
        view.setPivotY(view.getHeight() / 2);
        view.setRotation(rotation);
    }


}
